//
//  TicketDetailViewController.m
//  myhuibao
//
//  Created by 孙昕 on 14-3-11.
//  Copyright (c) 2014年 myhuibao. All rights reserved.
//

#import "TicketDetailViewController.h"
#import "SBJson.h"
#import "LoginViewController.h"
#import "Config.h"
#import "OMGToast.h"
#import "RequestLoadingView.h"
@interface TicketDetailViewController ()

@end

@implementation TicketDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [_lbTitle setBackgroundColor:[UIColor colorWithRed:174.0/255 green:0 blue:1.0/255 alpha:1]];
    [_btnGetTicket setBackgroundColor:[UIColor colorWithRed:174.0/255 green:0 blue:1.0/255 alpha:1]];
    [_vDetail setBackgroundColor:[UIColor colorWithRed:227.0/255 green:226.0/255 blue:226.0/255 alpha:1]];
    
    [self startRequest];
    
}

- (void)startRequest
{
    
    if(!loadingView)
    {
        loadingView = [[RequestLoadingView alloc]
                       initRequestLoadingView:self
                       queueFinishSelector:nil
                       viewFrame:LoadingViewFrame];
    }
    
    [self GetTicket];
    
    [loadingView addRequestToQueue:req];

    [loadingView startRequestQueue];
    
}

-(void)GetTicket
{
    NSURL *url=[NSURL URLWithString:url_ticketDetail];
    req=[ASIFormDataRequest requestWithURL:url];
    [req setPostValue:[NSString stringWithFormat:@"%d",_merchantTypeID] forKey:@"merchantType"];
    [req setPostValue:[NSString stringWithFormat:@"%d",_couponID] forKey:@"couponID"];
    [req setDelegate:self];
    [req setDidFinishSelector:@selector(finishGetTicket:)];
    
    if (!loadingView.bFirstRequest)
    {
        [req startAsynchronous];
    }

}

-(void)finishGetTicket:(ASIHTTPRequest*)request
{
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    NSDictionary *data = [dic valueForKey:@"data"];
    if([dic[@"status"] isEqualToString:@"SUCCESS"] )
    {
        _lbMerchantName.text=data[@"merchantName"];
        NSString *imageDataPath = [NSHomeDirectory() stringByAppendingPathComponent:[@"Library/Caches/" stringByAppendingString:data[@"picPath"]]];
        UIImage *ShowImage=nil;
        if (![[NSFileManager defaultManager] fileExistsAtPath:imageDataPath])
        {
            NSString *urlstr=[NSString stringWithFormat:@"%@%@",url_image,data[@"picPath"]];
            NSURL *url=[NSURL URLWithString:urlstr];
            NSData *dat=[NSData dataWithContentsOfURL:url];
            UIImage *image=[UIImage imageWithData:dat];
            if(image)
            {
                [dat writeToFile:imageDataPath atomically:YES];
                ShowImage=image;
            }
            else
            {
                if([data[@"couponTypeID"] intValue]==1)
                {
                    ShowImage=[UIImage imageNamed:@"daijin.jpg"];
                }
                else if([data[@"couponTypeID"] intValue]==2)
                {
                    ShowImage=[UIImage imageNamed:@"zhekou.jpg"];
                }
                else if([data[@"couponTypeID"] intValue]==3)
                {
                    ShowImage=[UIImage imageNamed:@"fan.jpg"];
                }
            }
        }
        else
        {
            ShowImage=[UIImage imageWithContentsOfFile:imageDataPath];
        }
        int height=320*ShowImage.size.height/ShowImage.size.width;
        CGRect frame=_imageView.frame;
        frame.size.height=height;
        _imageView.frame=frame;
        _imageView.image=ShowImage;
        frame=_lbTitle.frame;
        frame.origin.y=_imageView.frame.origin.y+_imageView.frame.size.height;
        _lbTitle.frame=frame;
        frame=_vDetail.frame;
        frame.origin.y=_lbTitle.frame.origin.y+_lbTitle.frame.size.height;
        _vDetail.frame=frame;
        frame=_texContent.frame;
        frame.origin.y=_vDetail.frame.origin.y+_vDetail.frame.size.height;
        _texContent.frame=frame;
        [_ScrollView setContentSize:CGSizeMake(320, _texContent.frame.origin.y+_texContent.frame.size.height)];
        _lbTitle.text=data[@"title"];
        _lbArea.text=data[@"merchantAddress"];
        _lbTime.text=[NSString stringWithFormat:@"有效期至：%@",data[@"endDate"]];
        downloadNum=[data[@"downloadNum"] intValue];
        _lbCount.text=[NSString stringWithFormat:@"下载次数：%d",downloadNum ];
        if([data[@"status"] intValue]==2)
        {
            _btnGetTicket.hidden=YES;
            CGRect frame= _vDetail.frame;
            frame.size.height-=_btnGetTicket.frame.size.height;
            _vDetail.frame=frame;
            frame=_texContent.frame;
            frame.origin.y-=_btnGetTicket.frame.size.height;
            _texContent.frame=frame;
            CGSize size=_ScrollView.contentSize;
            size.height-=_btnGetTicket.frame.size.height;
            [_ScrollView setContentSize:size];
        }
        [_texContent loadHTMLString:[data[@"content"] stringByReplacingOccurrencesOfString:@"\r\n" withString:@"<br/>"] baseURL:nil];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)OnBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)OnGetTicket:(id)sender {
    int memberId = [[Config Instance] getMemberId];
    if(memberId == 0)
    {
        LoginViewController  *view = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
        view.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:view animated:YES];
        return;
    }
    NSURL *url=[NSURL URLWithString:url_getticket];
    reqGet=[ASIFormDataRequest requestWithURL:url];
    [reqGet setPostValue:[NSString stringWithFormat:@"%d",[[Config Instance] getMemberId]] forKey:@"memberID"];
    [reqGet setPostValue:[NSString stringWithFormat:@"%@",[[Config Instance] getPassword]] forKey:@"password"];
    [reqGet setPostValue:[NSString stringWithFormat:@"%d",_couponID] forKey:@"couponID"];
    [reqGet setDelegate:self];
    [reqGet setDidFinishSelector:@selector(finishGetMyTicket:)];
    [reqGet startAsynchronous];
}

-(void)finishGetMyTicket:(ASIHTTPRequest*)request
{
    NSString *jsonStr = [request responseString];
    //NSLog(@"%@",jsonStr);
    NSDictionary *dic = [jsonStr JSONValue];
    if([dic valueForKey:@"log"]!=[NSNull null] && [[dic valueForKey:@"log"] compare:@"登录已经过期，请重新登录" options:1]==NSOrderedSame)
    {
        LoginViewController  *view = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
        //    view.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:view animated:YES];
        return;
    }
    else if([[dic valueForKey:@"status"] isEqualToString:@"ERROR"])
    {
        [OMGToast showWithText:@"领取失败！" bottomOffset:100];
        return;
    }
    NSDictionary *data= [dic valueForKey:@"data"];
    NSString *msg=nil;
    if([data[@"result"] intValue]==1)
    {
        msg=[NSString stringWithFormat:@"领取成功，使用特权码为：%@",data[@"couponCode"]];
        _lbCount.text=[NSString stringWithFormat:@"下载次数：%d",++downloadNum ];
    }
    else
    {
        msg=[NSString stringWithFormat:@"%@",data[@"msg"]];

    }
    UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                  message:msg
                                                 delegate:nil
                                        cancelButtonTitle:@"确定"
                                        otherButtonTitles:nil];
    [alert show];
}
@end
